package com.wctj.api.base.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;

/**
 * TODO DESCRIPTION
 *
 * @author zzl
 * @date 2022-01-04
 */
@Slf4j
public class JacksonUtil {

    private JacksonUtil() {
    }

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .registerModule(new JavaTimeModule());

    /**
     * 紧凑格式
     *
     * @param object
     * @return
     */
    public static String getNormalPatternJsonString(Object object) {
        String json = null;
        try {
            json = OBJECT_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("jackson格式化json字符串失败", e);
        }

        return json;
    }

    /**
     * 格式化
     *
     * @param object
     * @return
     */
    public static String getPrettyPatternJsonString(Object object) {
        String json = null;
        try {
            json = OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("jackson格式化json字符串失败", e);
        }

        return json;
    }

    public static <T> T parse(String content, Class<T> clazz) {
        T parse = null;
        try {
            parse = OBJECT_MAPPER.readValue(content, clazz);
        } catch (JsonProcessingException e) {
            log.error("jackson解析json字符串失败", e);
        }

        return parse;
    }

    public static <T> T parse(String content, TypeReference<T> typeReference) {
        T parse = null;
        try {
            parse = OBJECT_MAPPER.readValue(content, typeReference);
        } catch (JsonProcessingException e) {
            log.error("jackson解析json字符串失败", e);
        }

        return parse;
    }

}
